package com.example.message2;

import java.util.ArrayList;
import java.util.HashMap;

import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class AndroidXMLParsingActivity extends ListActivity {

	// All static variables
	static final String URL = "http://softeng.cs.uwosh.edu/students/cs342g2/php/pullMessages.php";
	// XML node keys
	static final String KEY_ITEM = "message"; // parent node
	static final String KEY_ID = "id";
	static final String KEY_FROM = "from";
	static final String KEY_TO = "to";
	static final String KEY_TEXT = "text";
	static final String KEY_READ = "read";
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		SharedPreferences settings = getSharedPreferences("preferences",0);
		int user=settings.getInt("curUser", -1);
		String password= settings.getString("curPassword","");
		
		ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();

		XMLParser parser = new XMLParser();
		String xml = parser.getXmlFromUrl(URL,user,password); 
		Document doc = parser.getDomElement(xml); 

		NodeList nl = doc.getElementsByTagName(KEY_ITEM);
		for (int i = 0; i < nl.getLength(); i++) {
			HashMap<String, String> map = new HashMap<String, String>();
			Element e = (Element) nl.item(i);
			map.put(KEY_ID, parser.getValue(e, KEY_ID));
			map.put(KEY_FROM, "From: " + parser.getValue(e, KEY_FROM));
			map.put(KEY_TO, parser.getValue(e, KEY_TO));
			map.put(KEY_TEXT, parser.getValue(e, KEY_TEXT));
			map.put(KEY_READ, parser.getValue(e, KEY_READ));
			menuItems.add(map);
		}
		ListAdapter adapter = new SimpleAdapter(this, menuItems,
				R.layout.list_item,
				new String[] { KEY_FROM, KEY_TEXT, KEY_TO }, new int[] {
						R.id.name, R.id.desciption});

		setListAdapter(adapter);

		// selecting single ListView item
		ListView lv = getListView();

		lv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// getting values from selected ListItem
				String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
				//String cost = ((TextView) view.findViewById(R.id.cost)).getText().toString();
				String description = ((TextView) view.findViewById(R.id.desciption)).getText().toString();
				
				// Starting new intent
				Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
				in.putExtra(KEY_FROM, name);
				//in.putExtra(KEY_TO, cost);
				in.putExtra(KEY_TEXT, description);
				startActivity(in);

			}
		});
		
		/*
		findViewById(R.id.button2).setOnClickListener(       		 
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						Intent myIntent = new Intent(AndroidXMLParsingActivity.this, MainActivity.class); 
						startActivityForResult(myIntent, 0);
						//close();
						AndroidXMLParsingActivity.this.finish();
					}
				});	

		findViewById(R.id.button1).setOnClickListener(       		 
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						Intent myIntent = new Intent(AndroidXMLParsingActivity.this, SendMessage.class); 
						startActivityForResult(myIntent, 0);
						//close();
						AndroidXMLParsingActivity.this.finish();
					}
				});	
*/
		
		
		
	}

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.message_menu, menu);
    return true;
    }



   @Override
    public boolean onOptionsItemSelected(MenuItem item) {
           
        // Handle item selection
        switch (item.getItemId()) {
            case R.id.send_message:
            	
            	Intent myIntent = new Intent(this, SendMessage.class); 
				startActivity(myIntent);
				//close();
			
                return true;
            case R.id.LogOut:
            	close();
            	return true;
            	
            default:
                return super.onOptionsItemSelected(item);
        }
    }


	
	public void close(){
		this.finish();
	}
	
	
	
	public class UserRegisterTask extends AsyncTask<String, String, Boolean> {

		@Override
		protected Boolean doInBackground(String... params) {
			// TODO: attempt authentication against a network service.
			Boolean success = false;
			ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();

			if (networkInfo != null && networkInfo.isConnected()) {
				ArrayList<NameValuePair> n = new ArrayList<NameValuePair>(2);
				n.add(new BasicNameValuePair("uid", params[0]));
				n.add(new BasicNameValuePair("password", params[1]));

				HttpClient httpClient = new DefaultHttpClient();
				HttpPost httppost = new HttpPost("http://softeng.cs.uwosh.edu/students/cs342g2/php/pullMessages.php?uid=1&password=password");
				// httppost.setEntity(new UrlEncodedFormEntity(n));

				try {
					httppost.setEntity(new UrlEncodedFormEntity(n));
					ResponseHandler<String> respondHandler = new BasicResponseHandler();
					String response = httpClient.execute(httppost,
							respondHandler);
					success = true;

				} catch (Exception e) {

				}
			}

			return success;
		}

	}
}